package com.villaday.idf.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.adapter.HomeDetailsSameAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.DividerGridItem;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.mzbanner.MZBannerView;
import com.villaday.idf.custom.mzbanner.holder.MZHolderCreator;
import com.villaday.idf.custom.mzbanner.holder.MZViewHolder;
import com.villaday.idf.model.TopicEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;


public class FindDetailsActivity extends BaseActivity implements OkHttpUtil.OnDataListener, MZBannerView.BannerPageClickListener, AbsRecyclerViewAdapter.OnItemClickListener {


    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    /* @BindView(R.id.banner)
     MZBannerView mMZBanner;*/
    /*@BindView(R.id.tv_page)
    TextView tvPage;*/
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_description)
    TextView tvDescription;
    @BindView(R.id.tv_addr)
    TextView tvAddr;
    @BindView(R.id.sdv_head)
    SimpleDraweeView sdvHead;
    @BindView(R.id.sdv)
    SimpleDraweeView sdv;

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_order_type)
    TextView tvOrderType;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.tv_h5)
    WebView tvH5;
    @BindView(R.id.tv_same)
    TextView tvSame;
    @BindView(R.id.tv_play)
    ImageView tvPlay;
    @BindView(R.id.rl_pho)
    RelativeLayout rlPho;
    @BindView(R.id.rv_video)
    RelativeLayout rvVideo;

    @BindView(R.id.banner)
    MZBannerView mMZBanner;
    @BindView(R.id.tv_page)
    TextView tvPage;

    @BindView(R.id.ll)
    LinearLayout ll;


    @BindView(R.id.rv_same)
    RecyclerView rvSame;

    private LoadingDialog loadingDialog;
    private String topicId;
    private Gson gson = new GsonBuilder().create();
    private TopicEntity.BodyEntity body;
    private TopicEntity topicEntity;
    private StatusLayoutManager statusLayoutManager;


    @Override
    protected int getViewResId() {
        return R.layout.activity_find_details;
    }

    @Override
    protected void init() {

        statusLayoutManager = setupDefaultStatusLayoutManager(ll, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");

                loadData();
            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });
        mMZBanner.getLayoutParams().height = (int) (PhoneUtil.getPhoneWidth(this) / 1.6);
        mMZBanner.requestLayout();
        topicId = getIntent().getStringExtra("topicId");
        ToolBarUtil.initToolBar(toolbarText, "发现", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    protected void loadData() {
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getFragmentManager(), "loading");
        OkHttpUtil.getJSON(this, Constant.URL.topic + topicId, this);


    }

    @OnClick({R.id.tv_order_type, R.id.tv_share, R.id.sdv, R.id.tv_play})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_order_type:
                break;
            case R.id.tv_share:
                break;
            case R.id.sdv:
                break;
            case R.id.tv_play:

                if (body != null && body.getVideo() != null && body.getVideo().getVideoUrl() != null) {
                    Intent intent = new Intent(this, VideoPlayActivity.class);

                    intent.putExtra("videoUrl", body.getVideo().getVideoUrl());
                    intent.putExtra("title", "返回详情");
                    intent.putExtra("photoUrl", body.getVideo().getPosterUrl());
                    intent.putExtra("des", body.getVideo().getDescription());
                    startActivity(intent);
                }


                break;
        }
    }

    @Override
    public void onResponse(String url, String json) {
        dismissLoading();
        if (statusLayoutManager != null) {

            statusLayoutManager.showSuccessLayout();
        }
        if (!TextUtils.isEmpty(json)) {
            if ((Constant.URL.topic + topicId).equals(url)) {
                LogeUtil.e("topicId", json);
                topicEntity = gson.fromJson(json, TopicEntity.class);
                if ("200".equals(topicEntity.getCode())) {
                    body = topicEntity.getBody();
                    initview(topicEntity);
                    initSimilarHouse(body);


                } else {
                    ToastUtil.initToast(this, topicEntity.getMsg());
                }

            }
        }
    }

    private void initSimilarHouse(TopicEntity.BodyEntity body) {
        if (TextUtils.isEmpty(body.getRecommendDescription())) {
            tvSame.setVisibility(View.GONE);
        } else {
            tvSame.setText(body.getRecommendDescription());

        }

        rvSame.setLayoutManager(new LinearLayoutManager(this));
        HomeDetailsSameAdapter homeDetailsSameAdapter = new HomeDetailsSameAdapter(this);
        rvSame.setAdapter(homeDetailsSameAdapter);

        rvSame.addItemDecoration(new DividerGridItem(this));
        homeDetailsSameAdapter.setOnItemClickListener(this);
        List<TopicEntity.BodyEntity.SimilarHouseListEntity> similarHouseList = new ArrayList<>();
        similarHouseList.addAll(body.getSimilarHouseList());
        homeDetailsSameAdapter.setData(similarHouseList);
    }

    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
        if (statusLayoutManager != null) {

            statusLayoutManager.showErrorLayout();
        }
        ToastUtil.initToast(this,"网络错误");
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    private void initview(TopicEntity topicEntity) {
        String tag = "";
        if (!(topicEntity.getBody().getTags() == null || topicEntity.getBody().getTags().size() == 0)) {

            for (int i = 0; i < topicEntity.getBody().getTags().size(); i++) {
                tag = new StringBuilder().append(tag).append("#").append(topicEntity.getBody().getTags().get(i)).append("#").append(" ").toString();
            }
        }
        tvTitle.setText(topicEntity.getBody().getTitle());
        tvDescription.setText(tag);
        if (TextUtils.isEmpty(topicEntity.getBody().getProvince()) &&TextUtils.isEmpty(topicEntity.getBody().getCity())){
            tvAddr.setVisibility( (TextUtils.isEmpty(topicEntity.getBody().getProvince()) &&TextUtils.isEmpty(topicEntity.getBody().getCity())?View.INVISIBLE:View.VISIBLE) );

        }else {
            tvAddr.setText(topicEntity.getBody().getProvince() + "·" + topicEntity.getBody().getCity());

        }

        tvName.setText(topicEntity.getBody().getMember().getNickName());
        sdvHead.setImageURI(topicEntity.getBody().getMember().getHeaderUrl() + "");
        tvOrderType.setText(topicEntity.getBody().getFavoriteCount() == null ? "0" : topicEntity.getBody().getFavoriteCount());
        tvShare.setText(topicEntity.getBody().getShareCount() == null ? "0" : topicEntity.getBody().getShareCount());
        sdv.setImageURI(TextUtils.isEmpty(topicEntity.getBody().getVideo().getVideoUrl()) ? topicEntity.getBody().getImageURL() + "" : topicEntity.getBody().getVideo().getPosterUrl());
        tvPlay.setVisibility(TextUtils.isEmpty(topicEntity.getBody().getVideo().getVideoUrl()) ? View.GONE : View.VISIBLE);
        if (TextUtils.isEmpty(topicEntity.getBody().getVideo().getVideoUrl())) {
            rlPho.setVisibility(View.VISIBLE);
            rvVideo.setVisibility(View.GONE);
            initBanner(topicEntity.getBody().getPicList());
        } else {
            rlPho.setVisibility(View.GONE);
            rvVideo.setVisibility(View.VISIBLE);
        }


        //tvH5.setText(Html.fromHtml(body.getHouse().getDetail(), new URLImageGetter(tvH5, getContext()), null));
        tvH5.getSettings().setJavaScriptEnabled(true);
        tvH5.setWebChromeClient(new WebChromeClient());
        imageFillWidth(tvH5, topicEntity.getBody().getContent().replace("<p><br></p><p><br></p>", ""));

    }

    private void initBanner(final List<String> imageURLs) {
        //添加Page点击事件
        mMZBanner.setBannerPageClickListener(this);
        //设置是否显示Indicator
        mMZBanner.setIndicatorVisible(false);

        // 设置数据
        tvPage.setText("1/" + imageURLs.size());
        mMZBanner.setPages(imageURLs, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
        mMZBanner.start();
        // 设置页面改变监听器
        mMZBanner.addPageChangeLisnter(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                try {
                    tvPage.setText(position + 1 + "/" + imageURLs.size());

                }catch (Exception ignored){

                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    /**
     * 处理图片视频填充手机宽度
     *
     * @param webView
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void imageFillWidth(WebView webView, String htmlStr) {
        //htmlStr.replace("height: 100%","height: auto");
        Document doc = Jsoup.parse(htmlStr);

        //修改视频标签
        Elements embeds = doc.getElementsByTag("embed");
        for (Element element : embeds) {
            //宽度填充手机，高度自适应
            element.attr("width", "100%").attr("height", "auto");
        }
        //webview 无法正确识别 embed 为视频，所以这里把这个标签改成 video 手机就可以识别了
        doc.select("embed").tagName("video");

        //控制图片的大小
        Elements imgs = doc.getElementsByTag("img");
        for (int i = 0; i < imgs.size(); i++) {
            //宽度填充手机，高度自适应

            String width = imgs.get(i).attr("width");
            if (!TextUtils.isEmpty(width)) {
                int phoneWidth = PhoneUtil.getPhoneWidth(this);

                try {
                    if (Integer.parseInt(width) > PhoneUtil.PixelsToDip(this, phoneWidth)) {
                        imgs.get(i).attr("width", "100%").attr("height", "auto");
                    }
                } catch (Exception e) {
                    continue;
                }


            } else {
                imgs.get(i).attr("style", "width:  100%; height: auto;");

            }
        }
        //控制图片的大小
        Elements video = doc.getElementsByTag("video");
        for (int i = 0; i < video.size(); i++) {
            //宽度填充手机，高度自适应
            video.get(i).attr("style", "width: 100%; height: auto;");
        }

     /*   //控制图片的大小
        Elements section = doc.getElementsByTag("section");
        for (int i = 0; i < section.size(); i++) {
            //宽度填充手机，高度自适应
            section.get(i).attr("style", "width: 100%; height: auto;");
        }*/
        webView.setWebContentsDebuggingEnabled(true);
        //加载使用 jsoup 处理过的 html 文本
        webView.loadDataWithBaseURL(null, doc.toString(), "text/html", "UTF-8", null);
    }

    @Override
    public void onPageClick(View view, int position) {

    }

    @Override//相似推荐
    public void onItemClick(View v, int position) {
        Intent intent = new Intent(this, HouseDetailsActivityFor3.class);
        intent.putExtra("houseId", body.getSimilarHouseList().get(position).getId());
        intent.putExtra("brokerAge", body.getSimilarHouseList().get(position).getBrokerAge());

        startActivity(intent);
    }

    public static class BannerViewHolder implements MZViewHolder<String> {
        private SimpleDraweeView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item_find, null);
            mImageView = (SimpleDraweeView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, String data) {
            // 数据绑定
            //mImageView.setImageURI(new Uri.Builder().scheme("res").path(String.valueOf(data)).build());
            mImageView.setImageURI(data);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mMZBanner.pause();//暂停轮播
    }

    @Override
    public void onResume() {
        super.onResume();
        mMZBanner.start();//开始轮播
    }
}
